package com.apache.servlet;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import com.apache.tools.StrUtil;

public class ResultFullFilter implements Filter {

	private final static String SERVLET_PACKAGE = "servletPackage";

	private ServletContainer servletContainer;
	private ServletContext servletContext;

	public void init(FilterConfig filterConfig) throws ServletException {
		String servletPackageStr = filterConfig.getInitParameter(SERVLET_PACKAGE);
		boolean mark = false;
		if (StrUtil.isNotNull(servletPackageStr)) {
			String[] servletPackages = servletPackageStr.split(",");
			servletContainer = new AnnotationServletContainer(servletPackages);
			servletContainer.initContainer();
			mark = true;
		} else {
			String servletClassStr = filterConfig.getInitParameter("servletClass");
			if (StrUtil.isNotNull(servletClassStr)) {
				String[] servletClasses = servletClassStr.split(",");
				servletContainer = new AnnotationServletContainer();
				servletContainer.initContainer(servletClasses);
				mark = true;
			}
		}
		if (!mark) {
			throw new RuntimeException("ResultFullFilter过滤器初始化参数［servletPackage/servletClass］不能为空");
		}

		servletContext = filterConfig.getServletContext();
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpReq = (HttpServletRequest) request;
		String uri = httpReq.getServletPath();
		ResultFullServletSupper servletBean = servletContainer.getServlet(uri);
		if (servletBean == null) {
			chain.doFilter(request, response);
		} else {
			HttpServlet servlet = servletBean.getServlet();
			if (servlet.getServletConfig() == null) { //第一次要调用servlet的init方法，注入自定义的ServletConfig
				servlet.init(new ResultFullServletConfig(servletBean.getName(), servletContext,
						new HashMap<String, String>()));
			}
			//初始化rest参数
			String[] params = servletContainer.getParamsInUri(uri);
			for (int i = 0, l = params.length; i < l; i++) {
				String p = params[i];
				request.setAttribute("PathAttr" + i, p);
			}
			servlet.service(request, response);
		}
	}

	public void destroy() {
		System.out.println("----------------ResultFullFilter destroy----------------");
	}

}
